<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="table">
        <Table
          @pageChange="getData"
          v-bind.sync="pages"
          :loading.sync="loading"
          :tableData="tableData"
          :tableConfig="tableConfig"
        >
          <template v-slot:operation="row">
            <div class="t_button">
              <el-button
                type="primary"
                icon="el-icon-view"
                @click="handleViews(row.data)"
                circle
              ></el-button>
              <el-button
                circle
                icon="el-icon-edit"
                type="success"
                @click="handleEdit(row.data)"
              >
              </el-button>
              <el-button
                circle
                icon="el-icon-connection"
                type="warning"
                @click="handleRole(row.data)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(row.data)"
                circle
              ></el-button>
            </div>
          </template>
          <template v-slot:headerButtons>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd()"
              >新 增
            </el-button>
          </template>
        </Table>
      </div>
      <div class="dialog">
        <!-- 角色新增、查看、修改弹窗 -->
        <Dialog ref="form" :formData.sync="form" :formConfig="formConfig">
          <template v-slot:formFooter>
            <el-button size="mini" @click="formConfig.dialogFormVisible = false"
              >取 消</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-if="formConfig.title !== '查看角色'"
              @click="addAndEdit()"
              >确 定</el-button
            >
          </template>
        </Dialog>
      </div>
      <div class="setRoleDialog">
        <!-- 权限更新弹窗 -->
        <el-dialog
          title="权限更新"
          :destroy-on-close="true"
          ref="dialog"
          :visible.sync="roleConfig.dialogFormVisible"
          width="60%"
        >
          <el-row>
            <el-col :span="24">
              <!-- <el-input placeholder="输入关键字进行过滤" v-model="filterText">
              </el-input> -->
            </el-col>
            <el-col :span="24">
              <el-tree
                :data="dataTree"
                show-checkbox
                node-key="id"
                :default-expanded-keys="[1]"
                :default-checked-keys="[2,3,4,5]"
                @check-change="handleCheckChange"
                :props="defaultProps"
              >
              </el-tree>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="roleConfig.dialogFormVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" size="mini" @click="uodateRole()"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
// import { parseTime } from "@/utils";
import storage from "@/utils/storage";

import {
  getRoleInfo,
  getRoleList,
  addRoleInfo,
  delRoleInfo,
  editRoleInfo,
  getMenuList,
  editRoleMenu
} from "@/api/role";
export default {
  components: {
    Table,
    Dialog
  },
  data() {
    return {
      formRules: this.$store.state.settings.formRules,
      dialogRoleVisible: false,
      //分页
      pages: {
        current: 1,
        size: 10,
        total: 0
      },
      //加载状态
      loading: false,
      //表格数据
      tableData: [],
      //表格配置项
      tableConfig: {
        border: true, //表格边框
        selection: false, //多选
        headerButtons: true, //表格顶部按钮slot
        pagination: true,
        columns: [
          //列配置项
          {
            label: "角色名称",
            value: "roleName"
          },
          {
            label: "角色标识",
            value: "roleLogo"
          },
          {
            label: "角色描述",
            value: "describe"
          },
          {
            label: "创建时间",
            value: "createTime"
          },
          {
            label: "更新时间",
            value: "updateTime"
          },
          {
            label: "操作",
            slot: "operation",
            width: "250px"
          }
        ]
      },
      roleData: {},
      //弹窗配置项
      roleConfig: {
        title: "更新权限",
        span: 20,
        width: "60%",
        dialogFormVisible: false,
        columns: [
          {
            label: "权限列表:",
            value: "roleIds",
            slot: "roleIds"
          }
        ]
      },
      dataTree: [], //所有权限数据
      //权限更新提交数据
      datas: [],
      //新增、查看、修改表单数据
      form: {},
      roleId: null,
      formConfig: {
        title: "新增",
        dialogFormVisible: false,
        columns: [
          {
            label: "角色名称",
            value: "roleName",
            rules: [this.$store.state.settings.formRules.required]
          },
          {
            label: "角色标识",
            value: "roleLogo",
            rules: [this.$store.state.settings.formRules.required]
          },
          {
            label: "角色描述",
            value: "describe",
            rules: [this.$store.state.settings.formRules.required]
          }
        ]
      },
      //树结构
      defaultProps: {
        children: "children",
        label: "resName"
      },
      //当前行数据
      rowData: {}
    };
  },
  mounted() {
    this.getData();

    this.getRoleTree();
  },
  watch: {},

  methods: {
    getData() {
      this.loading = true;
      getRoleList(
        Object.assign({
          current: this.pages.current,
          size: this.pages.size
        })
      ).then(res => {
        // console.log(res);
        this.loading = false;
        this.tableData = res.data;
        this.pages.total = res.total;
      });
    },
    handleClose() {
      this.dialogRoleVisible = false;
    },
    //新增弹窗
    handleAdd() {
      this.form = {
        roleName: "",
        roleLogo: "",
        describe: ""
      };
      this.formConfig.title = "新增角色";
      this.formConfig.disabled = false;
      this.formConfig.dialogFormVisible = true;
    },
    //修改弹窗
    handleEdit(row) {
      this.roleId = row.id;
      getRoleInfo(row.id).then(res => {
        this.form = res;
        this.formConfig.title = "修改角色";
        this.formConfig.disabled = false;
        this.formConfig.dialogFormVisible = true;
      });
    },
    //查看弹窗
    handleViews(row) {
      getRoleInfo(row.id).then(res => {
        this.form = res;
        this.formConfig.title = "查看角色";
        this.formConfig.disabled = true;
        this.formConfig.dialogFormVisible = true;
      });
    },
    //更新权限
    handleRole(row) {
      this.getByIdRoleTree(row.id);
      this.rowData = JSON.parse(JSON.stringify(row));
    },
    //新增、修改
    addAndEdit() {
      if (this.$refs.form.fromValidate()) {
        //验证规则
        if (this.formConfig.title === "新增角色") {
          //新增
          addRoleInfo(this.form).then(res => {
            console.log(res);
            if (res.code === 200) {
              this.$message({
                message: "新增角色成功！",
                type: "success"
              });
              this.formConfig.dialogFormVisible = false;
              this.getData();
            } else {
              this.$message({
                message: "新增角色失败！",
                type: "error"
              });
            }
          });
        } else {
          //修改
          delete this.form.createTime;
          delete this.form.id;
          delete this.form.roleId;
          editRoleInfo({ id: this.roleId, data: this.form }).then(res => {
            console.log(res);
            if (res.code === 200) {
              this.$message({
                message: "修改角色成功！",
                type: "success"
              });
              this.formConfig.dialogFormVisible = false;
              this.roleId = null;
              this.getData();
            } else {
              this.$message({
                message: "修改角色失败！",
                type: "error"
              });
            }
          });
        }
      }
    },
    //删除角色
    handleDelete(row) {
      const h = this.$createElement;
      this.$confirm("此操作将永久删除" + row.roleName + ", 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delRoleInfo(row.id).then(res => {
            // console.log(res);
            if (res.code === 200) {
              this.$notify({
                title: "Tips",
                message: "删除角色成功！",
                type: "success"
              });
              this.getData();
            } else {
              this.$notify.error({
                title: "Tips",
                message: "删除角色失败！"
              });
            }
          });
        })
        .catch(() => {
          this.$notify.info({
            title: "Tips",
            message: "取消删除！"
          });
          // this.$message({
          //   type: "info",
          //   message: ""
          // });
        });
    },
    //更新权限
    uodateRole() {
      let roleArr = [];
      roleArr.push(...this.$refs["treeKey"].getCheckedKeys());
      roleArr.push(...this.$refs["treeKey"].getHalfCheckedKeys());
      let roleKeys = "";
      roleArr.forEach((item, index) => {
        if (index === roleArr.length - 1) {
          roleKeys += item + "";
        } else {
          roleKeys += item + ",";
        }
      });
      console.log(roleArr);
      console.log(roleKeys);
      editRoleMenu({ resouceIds: roleArr, roleId: this.rowData.id }).then(
        res => {
          console.log(res);
          if (res.data) {
            this.$message({
              message: "更新权限成功！",
              type: "success"
            });
          } else {
            this.$message({
              message: "更新权限失败！",
              type: "error"
            });
          }
        }
      );
    },
    //树多选
    handleCheckChange(data, checked, indeterminate) {
      console.log(data.id);
      // console.log(checked);
      // console.log(indeterminate);
    },
    getRoleTree() {
      let menusList = storage.getStorage("menus");
     
      getMenuList().then(res => {
        this.dataTree = res.data;
        this.datas = menusList;
        console.log(this.datas);
      });
    },
    getByIdRoleTree(id) {
      // console.log(id);
      this.roleConfig.dialogFormVisible = true;
      // setResList(id).then((res) => {
      //   console.log(res);
      //   this.roleConfig.dialogFormVisible = true;
      //   this.$nextTick(function () {
      //     for (let i = 0; i < res.length; i++) {
      //       this.$refs["treeKey"].setChecked(res[i], true);
      //     }
      //   });
      // });
    }
  }
};
</script>
